package com.ch.web.controller;

import com.ch.web.requestDto.xyUser.XyUserEditUserInfoReq;
import com.ch.web.entity.user.XyUserEntity;
import com.ch.web.service.XyUserService;
import com.ch.web.utils.ColaBeanUtils;
import com.ch.web.utils.PageUtils;
import com.ch.web.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

/**
 * @author chenHao
 * @email 1429542285@qq.com
 * @date 2022-04-27 22:59:18
 */
@RestController
@RequestMapping("xy/user")
public class XyUserController {
    @Autowired
    private XyUserService xyUserService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = xyUserService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{userId}")
    public R info(@PathVariable("userId") Long userId) {
        XyUserEntity xyUser = xyUserService.getById(userId);

        return R.ok().put("xyUser", xyUser);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody XyUserEntity xyUser) {
        xyUserService.save(xyUser);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody XyUserEntity xyUser) {
        xyUserService.updateById(xyUser);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] userIds) {
        xyUserService.removeByIds(Arrays.asList(userIds));
        return R.ok();
    }

    /**
     * 修改信息
     */
    @RequestMapping("/editUserInfo")
    public R editUserInfo(@RequestBody XyUserEditUserInfoReq req, HttpServletRequest request) {
        return xyUserService.editUserInfo(ColaBeanUtils.copyObject(req, XyUserEntity::new), request) ? R.ok() : R.error("账号禁用或者已经被封禁");
    }

    /**
     * 校验密码
     */
    @GetMapping("/checkPassword")
    public R checkPassword(@RequestParam("oldPassword") String oldPassword, HttpServletRequest request) {
        if (StringUtils.isBlank(oldPassword)) {
            return R.error("密码不能为空");
        }
        return R.okOrError(xyUserService.checkPassword(oldPassword, request));
    }

    @GetMapping("/updatePassword")
    public R updatePassword(@RequestParam("newPassword") String newPassword, HttpServletRequest request) {
        if (!StringUtils.isBlank(newPassword)) {
           xyUserService.updatePassword(newPassword,request);
        }
        return R.error("新密码不能为空");
    }
}
